package server

import (
	"cloud_worm/access/server/srvbiz"
	"cloud_worm/util/unet/usocket"
	"cloud_worm/access/config"
	"fmt"
	"github.com/golang/glog"
	"cloud_worm/access/server/rpcbiz"
	"cloud_worm/access/server/rpcclient"
	"sync"
)

func AccessSrv() error {
	mgr := new(srvbiz.ServiceManage)

	usocket.TlsServerInstance().SetTlsServer(
		fmt.Sprintf("%s:%s", config.ConfInst.LocalAddr, config.ConfInst.Server.AccessPort),
		config.ConfInst.TLSCertInfo.PemFile,
		config.ConfInst.TLSCertInfo.KeyFile,
		mgr,
	)

	if err := usocket.TlsServerInstance().Listen(); err != nil {
		return err
	}

	glog.Infof("start access server '%s:%s' loop.", config.ConfInst.LocalAddr, config.ConfInst.Server.AccessPort)
	return nil
}

func RpcSrv() error {
	rpcSrv := rpcbiz.RpcServer{
		Address: fmt.Sprintf("%s:%s", config.ConfInst.LocalAddr, config.ConfInst.Server.RpcPort),
		PemFile: config.ConfInst.TLSCertInfo.PemFile,
		KeyFile: config.ConfInst.TLSCertInfo.KeyFile,
	}
	err := rpcSrv.RpcServe()
	if err != nil {
		return err
	}

	glog.Infof("start rpc server '%s:%s' loop.", config.ConfInst.LocalAddr, config.ConfInst.Server.RpcPort)
	return nil
}

func StartPushClient(wg *sync.WaitGroup) error {
	rpcclient.PushClient.ServerAddr = config.ConfInst.Remote.WebSrv
	err := rpcclient.PushClient.Loop(wg)
	if err != nil {
		return err
	}

	glog.Infof("start push client '%s' loop.", config.ConfInst.Remote.WebSrv)
	return nil
}

